# -*- coding: utf-8 -*-
"""
controller base for admin
"""

import tornado.web
from framework.controller import Controller
from models.admin import AdminModel
from framework.session import Session
import hashlib
import base64
import uuid

class AdminController(Controller):
    """admin login check controller"""

    _user = dict()

    def __init__(self, application, request, **kwargs):
        """call tornado.web"""
        super(AdminController, self).__init__(application, request, **kwargs)

    # Entry points
    def initialize(self):
        """admin login"""
        if self.current_user:
            if not self.current_user.get('type'):
                err = dict(err=1, msg=u'无权限访问')
                self.ajax_out(**err)
                return False
        return True

    @tornado.web.authenticated
    def get(self):
        """default get"""
        self.write_error(404)

    def get_current_user(self):
        """user login auth handler"""
        thor = self.get_secure_cookie("thor")
        if not thor:
            thor = base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes)
            self.set_secure_cookie('thor', thor)
        sess = Session(thor)
        # admin logined
        user = sess.get_all()
        if user:
            return user
        track_nick = self.get_secure_cookie("tracknick")
        token = self.get_secure_cookie("token")
        salt = self.request.remote_ip + self.request.headers['User-Agent']
        if (not track_nick) or (not token) or (not salt):
            return
        self._user = AdminModel().find_one({"name": track_nick})
        # not find admin
        if not self._user:
            return
        # admin type not aollow login
        if not self._user.get('type'):
            return
        # check admin login
        if self.cookie_login(token, salt):
            # tornado.web.RequestHandler.current_user = user
            sess.set_hmset(self._user)
            return self._user
        else:
            return

    def cookie_login(self, token, salt):
        """login from cookie"""
        md_5 = hashlib.md5()
        md_5.update(salt + self._user.get('pass') + self._user.get('name'))
        pw = md_5.hexdigest()
        if pw == token:
            return True
        else:
            return False

    def render(self, template_name, **kwargs):
        """
        join user
        :param template_name: 
        :param kwargs: 
        :return: 
        """
        user = dict()
        if self.current_user:
            user['user'] = self.current_user
        kwargs.update(user)
        super(AdminController, self).render(template_name, **kwargs)
